import { Box, Divider, HorizontalStack, Link, Text, VerticalStack } from "@shopify/polaris"
import { useEffect, useState } from "react"
import GetPrettifyEndpoint from '@/apps/dashboard/pages/observe/GetPrettifyEndpoint';
import GithubSimpleTable from "@/apps/dashboard/components/tables/GithubSimpleTable";

function Issue({ index, issueDetails, isLast }) {
    const [vulnerableApisState, setVulnerableApisState] = useState([])

    const removeTrailingQuotes = (str) => {
        return str.replace(/['"]+/g, '')
    }

    const getTestResultLink = () => {
        if (issueDetails.vulnerableTestingRunResults.length === 0) {
            return ''
        }

        const firstVulnerableApi = issueDetails.vulnerableTestingRunResults[0]
        const testRunResultSummaryHexId = firstVulnerableApi.testRunHexId
        const testRunId = firstVulnerableApi.hexId  

        return `/dashboard/testing/${testRunResultSummaryHexId}/result/${testRunId}`
    }
    const testResultLink = getTestResultLink()

    const name = issueDetails?.name
    const testName = issueDetails?.testName
    const issueDescription = removeTrailingQuotes(issueDetails?.issueDescription)
    const issueImpact = removeTrailingQuotes(issueDetails?.issueImpact)

    const vulnerableApisCount = issueDetails?.vulnerableTestingRunResults.length
    
    const resourceName = {
        singular: 'API',
        plural: 'APIs',
    };

    const apisHeader = (
             <HorizontalStack align="space-between">
                <Text variant="headingXs" fontWeight='bold'>{vulnerableApisCount} {vulnerableApisCount === 1 ? resourceName.singular : resourceName.plural} affected</Text>
                <Link url={testResultLink} removeUnderline target="_blank">
                    <Text variant='bodyMd'>See in Akto</Text>
                </Link>   
            </HorizontalStack>
       
    )
    const headers = [
        {
            text: apisHeader,
            title: apisHeader,
            value: 'apiDetails',
            textValue: 'apiDetailsText'
        }
    ]

    useEffect(() => {
        let vulnerableApis = issueDetails?.vulnerableTestingRunResults.map((vulnerableApi, index) => {
            const { url, method } = vulnerableApi.apiInfoKey
    
            const apiDetails = (
                <GetPrettifyEndpoint method={method} url={url} isNew={false} />            
            )
    
            return {
                key: index,
                apiDetailsText: `${method} ${url}`,
                apiDetails: apiDetails,
            }
        })

        const VULNERABLE_APIS_LIMIT = 5
  
        if (vulnerableApis.length > VULNERABLE_APIS_LIMIT) {
            const moreApisText = `+ ${vulnerableApis.length - VULNERABLE_APIS_LIMIT} more`
            vulnerableApis = vulnerableApis.slice(0, VULNERABLE_APIS_LIMIT)

            vulnerableApis.push({
                key: VULNERABLE_APIS_LIMIT + 1,
                apiDetailsText: "+more",
                apiDetails: <Text variant='bodySm' fontWeight="bold" color="subdued">{moreApisText}</Text>
            })
        }
    
        setVulnerableApisState(vulnerableApis)
    }, [])

    return (
        <Box id={name} paddingBlockStart={ index === 0 ? 0 : 4}>
            <VerticalStack gap="4">
                <Text variant='headingSm'>
                    {index + 1}. {testName}
                </Text>

                <Text variant='bodySm' color='subdued'>
                    {issueDescription}
                </Text>

                <GithubSimpleTable
                    key="table"
                    data={vulnerableApisState}
                    resourceName={resourceName}
                    headers={headers}
                    useNewRow={true}
                    condensedHeight={true}
                    hideQueryField={true}
                    headings={headers}
                    hidePagination={true}
                    showFooter={false}
                />

                <VerticalStack gap="1">
                    <Text variant='headingXs'>
                        Why is this a problem?
                    </Text>
                    <Text variant='bodySm' color='subdued'>
                        {issueImpact}
                    </Text>
                </VerticalStack>

                {!isLast ? <Divider />: null}
            </VerticalStack>
        </Box>
    )
}

export default Issue